package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.mapper.NewsEntityMapper;
import org.chen.model.NewsEntity;
import org.chen.model.dto.NewsQueryDTO;
import org.chen.service.INewsEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class NewsEntityServiceImpl extends ServiceImpl<NewsEntityMapper, NewsEntity> implements INewsEntityService {
    @Autowired
    private NewsEntityMapper newsMapper;

    public Page<NewsEntity> getNewsList(NewsQueryDTO query) {
        Page<NewsEntity> page = new Page<>(query.getPage(), query.getRows());
        LambdaQueryWrapper<NewsEntity> wrapper = new LambdaQueryWrapper<NewsEntity>()
                .eq(StringUtils.isNotEmpty(query.getCategory()), NewsEntity::getCategory, query.getCategory())
                .eq(StringUtils.isNotEmpty(query.getLanguage()), NewsEntity::getLanguage, query.getLanguage())
                .eq(query.getStatus() != null, NewsEntity::getStatus, query.getStatus())
                .orderByDesc(NewsEntity::getCreateTime);
        return newsMapper.selectPage(page, wrapper);
    }

    @Transactional
    public void saveNews(NewsEntity news) {
        if (news.getId() == null) {
            newsMapper.insert(news);
        } else {
            newsMapper.updateById(news);
        }
    }

    @Transactional
    public void publishNews(Long id) {
        NewsEntity news = new NewsEntity();
        news.setId(id);
        news.setStatus(1);
        news.setPublishTime(new Date());
        newsMapper.updateById(news);
    }

    @Transactional
    public void offlineNews(Long id) {
        NewsEntity news = new NewsEntity();
        news.setId(id);
        news.setStatus(2);
        newsMapper.updateById(news);
    }

    @Transactional
    public void deleteNews(Long id) {
        newsMapper.deleteById(id);
    }
}
